package com.gmall.search.service;

import com.gmall.client.feign.ProductFeignClient;
import com.gmall.client.feign.TrademarkFeignClient;
import com.gmall.common.result.Result;
import com.gmall.model.product.BaseTrademark;
import com.gmall.model.product.SkuInfo;
import com.gmall.model.product.dto.Category123IdNameDTO;
import com.gmall.model.search.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service

public class ESSyncService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    TrademarkFeignClient trademarkFeignClient;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**
     * 每5秒执行一次
     * 启动时间 8:25
     * 到达了8:30  第一次同步  ，获取lastSyncDateTime 为空，获取的是全量数据，同步到ES
     * 记录lastSyncDateTime = 8：30
     *
     * 时间来到了8：35  第二次同步  ，获取lastSyncDateTime 为8：30，获取的是增量数据，在8：30 之后修改的数据，同步到ES
     *
     * 记录lastSyncDateTime = 8：35
     *
     * 修改SKU的某条数据 8：37
     * 时间来到了8：40  第三次同步  ，获取lastSyncDateTime 为8：35，获取的是增量数据，在8：35 之后修改的数据，一条，同步到ES
     *记录lastSyncDateTime = 8：40
     */

    private int count = 0;
    @Scheduled(cron = "0/30 * * * * ?")
    public void syncDB2ES(){
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("START ===== 第" + (++count) + " 次同步 当前时间：" + sdf.format(now));

        /**
         * {
         *  "lastSyncDateTime":2024-08-12 12:23:05
         * }
         */
        Map serachMap = new HashMap<>();
        //第1步 获取上次同步时间
        Date lastSyncDateTime = (Date) redisTemplate.opsForValue().get("lastSyncDateTime");
        System.out.println("获取上次同步时间："+lastSyncDateTime);
        if(lastSyncDateTime==null){
            serachMap.put("lastSyncDateTime","");
        }else{
            serachMap.put("lastSyncDateTime",sdf.format(lastSyncDateTime));
        }

        //2.查询在lastSyncDateTime之后修改的数据
        System.out.println("开始查询在"+lastSyncDateTime+"之后修改的数据");
        List<SkuInfo> skuInfoListAfterDateTime =
                productFeignClient.getSkuInfoListAfterDateTime(serachMap);//全量数据或者增量数据
        //3 返回增量数据
        skuInfoListAfterDateTime.forEach(skuInfo -> {
            Goods goods = new Goods();
            goods.setId(skuInfo.getId());

            Result<Category123IdNameDTO> category123IdNameDTOResult
                    = productFeignClient.getCategory123IdNameDTO(skuInfo.getCategory3Id());
            if(category123IdNameDTOResult.isOk()){
                Category123IdNameDTO category123IdNameDTO = category123IdNameDTOResult.getData();

                if(category123IdNameDTO!=null){
                    goods.setCategory1Id(category123IdNameDTO.getCategory1Id());//2, 30, 192
                    goods.setCategory2Id(category123IdNameDTO.getCategory2Id());
                    goods.setCategory3Id(category123IdNameDTO.getCategory3Id());
                    goods.setCategory1Name(category123IdNameDTO.getCategory1Name());
                    goods.setCategory2Name(category123IdNameDTO.getCategory2Name());
                    goods.setCategory3Name(category123IdNameDTO.getCategory3Name());
                }
            }

            goods.setTitle(skuInfo.getSkuName() + " " + skuInfo.getSkuDesc());
            goods.setTmId(skuInfo.getTmId());
            goods.setTmName(skuInfo.getTmName());
            Result<BaseTrademark> result = trademarkFeignClient.getBaseTrademark(skuInfo.getTmId());
            if(result.isOk()){
                goods.setTmLogoUrl(result.getData().getLogoUrl());
            }
            goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setCreateTime(skuInfo.getCreateTime());
            goods.setUpdateTime(skuInfo.getUpdateTime());

            //4、将返回的数据同步到ES
            System.out.println("将返回的数据同步到ES：" + goods);
            elasticsearchRestTemplate.save(goods);
        });
        //5. 更新最后同步的时间
        System.out.println("END ===== 保存上次同步的时间：" + sdf.format(now));
        redisTemplate.opsForValue().set("lastSyncDateTime",now);

    }
}
